using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;

namespace StartMenuSearcher
{
	internal class StartMenuReader
	{
		List<Shortcut> shortcuts;

		public StartMenuReader()
		{
			RefreshShortcuts();
		}

		private void RefreshShortcuts()
		{
			shortcuts = new List<Shortcut>();

			IDictionary<Shortcut, object> foundShortcuts = new Dictionary<Shortcut, object>(new ShortcutComparator()); //used as a set.

			string currentUserPrograms = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
			string allUsersPrograms = Environment.GetEnvironmentVariable("ALLUSERSPROFILE") + "\\Start Menu";

			foreach (string s in Directory.GetFiles(allUsersPrograms, "*.lnk", SearchOption.AllDirectories))
			{
				HandleShortcut(s, foundShortcuts);
			}

			foreach (string s in Directory.GetFiles(currentUserPrograms, "*.lnk", SearchOption.AllDirectories))
			{
				HandleShortcut(s, foundShortcuts);
			}

			shortcuts.Sort();
		}

		private void HandleShortcut(string shortcutPath, IDictionary<Shortcut, object> foundShortcuts)
		{
			Shortcut s = new Shortcut(shortcutPath);
			
			if (!foundShortcuts.ContainsKey(s))
			{
				if (s.Path.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase))
				{          
					shortcuts.Add(s);
					foundShortcuts.Add(s, null);
				}
			}
		}

		public object[] GetListBoxItems(string filter)
		{
			List<Shortcut> ret = new List<Shortcut>();

			foreach (Shortcut s in shortcuts)
			{
				if (s.Matches(filter))
				{
					ret.Add(s);
				}
			}

			return ret.ToArray();
		}
	}
}
